﻿-- =============================================
-- Author:		GMH
-- Create date: 
-- Description:	
-- =============================================
CREATE PROCEDURE spGuardaSoporte
	@pnIdSoporte		INT,
	@psAsunto			VARCHAR(500),
	@pnIdEstatus		INT,
	@pnIdLaboratorio	INT,
	@pnIdSucursal		INT
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @nSeProcesa INT
	
	SET @nSeProcesa = 0
	IF @pnIdSoporte IS NULL
	BEGIN
		--SELECT @pnIdSoporte = ISNULL(MAX(IdSoporte),0) + 1 FROM dbo.Soporte
		INSERT INTO dbo.Soporte
				( --IdSoporte ,
				  Asunto ,
				  FechaSoporte ,
				  IdEstatus ,
				  IdLaboratorio ,
				  IdSucursal
				)
		VALUES  ( --@pnIdSoporte , -- IdSoporte - int
				  @psAsunto , -- Asunto - nvarchar(500)
				  GETDATE() , -- FecchaSoporte - datetime
				  1 , -- IdEstatus - int
				  @pnIdLaboratorio , -- IdLaboratorio - int
				  @pnIdSucursal  -- IdSucursal - int
				)
		SET @pnIdSoporte = @@IDENTITY
	END
	ELSE
	BEGIN
		IF @pnIdEstatus = 2
		BEGIN
			IF EXISTS(SELECT 1 FROM dbo.Soporte WHERE IdSoporte = @pnIdSoporte AND IdEstatus = 1)
			BEGIN
				UPDATE	dbo.Soporte
				SET		IdEstatus = @pnIdEstatus
				WHERE	IdSoporte = @pnIdSoporte
				
				SET @nSeProcesa = 1
			END
		END
		ELSE
		BEGIN
			UPDATE	dbo.Soporte
			SET		IdEstatus = @pnIdEstatus
			WHERE	IdSoporte = @pnIdSoporte
		END
	END
	
	SELECT @pnIdSoporte IdSoporte, @nSeProcesa SeProcesa

	SET NOCOUNT OFF;
END